Skip to content

Fix orphaned Laminar traces from cross-async-context conversations - #3113

Merged
neubig merged 5 commits into
mainfrom
fix/observability-cross-context-trace-propagation
May 8, 2026
Merged

neubig merged 5 commits into
mainfrom
fix/observability-cross-context-trace-propagation

Conversation

@neubig

@neubig neubig commented May 7, 2026 •

Copy link
Copy Markdown
Member

Problem

While auditing trace ingestion at https://laminar.app.all-hands.dev/, ~63% of conversations show up as orphaned/split traces.

In a 24h window (520 traces, last 14d):

top_span_name count session_id set?
conversation (root) ✅ 193 100%
conversation.send_message 163 0%
conversation.run 151 0%
tools/call create_pr 6 0%
litellm.completion 5 0%

The orphan spans have parent_span_id = 00000000-0000-0000-0000-000000000000 and contain real LLM/tool data — i.e. successful agent runs are being torn into 2-3 unrelated traces in the dashboard, with no session_id to stitch them back together.

Root cause

BaseConversation._start_observability_span calls Laminar.start_active_span("conversation"), which attaches the OTel context using contextvars.attach(). From the upstream Laminar docstring (verbatim):

Note that ending the started span in a different async context yields unexpected results. When propagating spans across different async or threading contexts, it is recommended to either:

  • Make sure to start and end the span in the same async context or thread, or
  • Use Laminar.start_span + Laminar.use_span where possible.

contextvars only propagate to tasks created after the attach, on the same thread. Pre-existing async tasks (FastAPI handlers, websocket loops, anything RemoteConversation does) don't see the parent. When such a task calls a method decorated with @observe(...) — send_message, run, generate_title, agent.step, MCPToolExecutor.call_tool — it starts a fresh root trace and the conversation is silently torn apart.

A second related bug: SpanManager is a process-wide LIFO stack. Two concurrent Conversation instances corrupt each other — closing one pops whichever span happens to be on top.

Fix

Switch to the upstream-recommended start_span + use_span pattern:

  1. RootSpan owned by the conversation. BaseConversation stores its root span on self._observability_root_span instead of pushing onto a global stack. start_root_span uses Laminar.start_span (no implicit context attach). session_id is applied via a brief use_span window so it lands on trace metadata.
  2. @observe re-attaches the root span at every entry point. The decorator wrapper inspects the first positional arg (self) for an _observability_root_span, and if present wraps the call in Laminar.use_span(...). Nested @observe'd calls and lmnr's auto-instrumentation inherit the right parent automatically.
  3. Backwards-compat shims kept. SpanManager, start_active_span, end_active_span are now thin wrappers around the new primitive, so anything outside the SDK that imported them still works (just without the global-collision footgun).

Effect on the trace shape

Before:

trace A: conversation                (root, has session_id, tokens=0)
trace B: conversation.send_message   (orphan, no session_id)
trace C: conversation.run            (orphan, no session_id)
         └─ agent.step
            ├─ litellm.completion
            └─ TerminalAction

After:

trace A: conversation                (root, has session_id, accumulates cost/tokens)
         ├─ conversation.send_message
         │  └─ litellm.completion
         └─ conversation.run
            └─ agent.step
               ├─ litellm.completion
               └─ TerminalAction

Tests

Three new regression tests in tests/sdk/observability/test_laminar.py:

  • test_observe_calls_use_span_with_owner_root_span_on_sync — sync @observe'd methods re-attach the owner's root span via Laminar.use_span.
  • test_observe_calls_use_span_with_owner_root_span_on_async — async @observe'd methods re-attach even when invoked from a freshly-created asyncio.Task with an empty contextvars.Context (the cross-context bug repro).
  • test_two_concurrent_conversations_do_not_collide — two Conversation instances get independent root spans and ending one does not affect the other.

All 28 observability tests pass locally; full SDK suite is running and I'll update this PR with the result before un-drafting.

Risk assessment

  • Behavior change visible in Laminar: orphan trace counts drop, child spans now appear under the right parent. No callers should rely on the old orphan behavior.
  • API surface: only adds public RootSpan / start_root_span / end_root_span. start_active_span / end_active_span / SpanManager are kept as functionally-equivalent shims.
  • Hot path: the observe wrapper now does one getattr and (when observability is enabled and the owner has a root span) a Laminar.use_span per call. That's roughly the same work start_active_span was doing internally; it's just moved to the call site so it works across async/thread boundaries. Negligible perf impact.
  • Async correctness: the new pattern is the one Laminar themselves recommend in their own docstrings. Any failure inside use_span is logged at debug and the wrapped function is still called, so observability errors can never break the SDK.

Why this is structural, not transient

The 63% orphan rate is determined by how callers use the SDK, not by data freshness. Every caller that constructs a Conversation in one task and invokes send_message/run from a different task hits this — RemoteConversation is one such caller by design. Waiting longer in production won't reduce the orphan rate.


Marking as draft for review — happy to iterate on naming or scope.

This PR was opened by an AI agent (OpenHands) on behalf of @neubig.

@neubig can click here to continue refining the PR


Agent Server images for this PR

• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server

Variants & Base Images

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:1253592-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-1253592-python \
  ghcr.io/openhands/agent-server:1253592-python

All tags pushed for this build

ghcr.io/openhands/agent-server:1253592-golang-amd64
ghcr.io/openhands/agent-server:1253592-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:1253592-golang-arm64
ghcr.io/openhands/agent-server:1253592-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:1253592-java-amd64
ghcr.io/openhands/agent-server:1253592-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:1253592-java-arm64
ghcr.io/openhands/agent-server:1253592-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:1253592-python-amd64
ghcr.io/openhands/agent-server:1253592-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:1253592-python-arm64
ghcr.io/openhands/agent-server:1253592-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:1253592-golang
ghcr.io/openhands/agent-server:1253592-java
ghcr.io/openhands/agent-server:1253592-python

About Multi-Architecture Support

  • Each variant tag (e.g., 1253592-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., 1253592-python-amd64) are also available if needed

Production traces show ~63% of conversations end up split across multiple
top-level Laminar traces: 327/520 traces in a 24h sample have
top_span_name in {conversation.send_message, conversation.run,
litellm.completion} with parent_span_id=00000000…, and 100% of those
orphans have empty session_id.

Root cause: the SDK starts the conversation root span via
Laminar.start_active_span in BaseConversation.__init__ and stores it in
a process-global SpanManager LIFO stack. start_active_span attaches the
OTel context using contextvars, which only propagates to tasks created
*after* the attach, on the *same* thread. When send_message / run /
generate_title are invoked from a different asyncio task or thread
(e.g. FastAPI handlers, websocket loops, RemoteConversation callers),
the @observe-decorated method does not see the conversation as its
parent and starts a fresh root trace. The Laminar SDK explicitly warns
against this pattern and recommends start_span + use_span instead.

A second, related bug: the global LIFO SpanManager corrupts state when
multiple Conversations are alive concurrently — closing one pops
whichever span happens to be on top.

Fix:
- Replace the global SpanManager with a per-conversation RootSpan owned
  by BaseConversation as self._observability_root_span.
- Create the root via Laminar.start_span (no implicit context attach).
- Have the @observe wrapper inspect the first positional arg for an
  _observability_root_span attribute and re-attach it via
  Laminar.use_span at every entry point. Nested @observe and lmnr
  auto-instrumented spans automatically inherit the right parent.
- Apply session_id by briefly entering use_span at construction time so
  it lands on the trace metadata.
- Keep SpanManager / start_active_span / end_active_span as deprecated
  shims for backwards compatibility.

Add three regression tests:
- sync entry points re-attach the owner's root span;
- async entry points re-attach the owner's root span even when invoked
  from a freshly-created asyncio.Task with an empty contextvars.Context;
- two concurrent conversations get independent root spans and ending
  one does not affect the other.

Co-authored-by: openhands <openhands@all-hands.dev>
@neubig neubig added the bug Something isn't working label May 7, 2026 — with OpenHands AI
@github-actions

github-actions Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

The previous tests patched start_active_span / end_active_span on the
base module; those names are still exported (as deprecated shims) but
BaseConversation now calls start_root_span / end_root_span. Update the
patches and assertions to target the new function names, and add an
idempotency assertion: a second _start_observability_span on an
already-started conversation must not start a second root span.

Co-authored-by: openhands <openhands@all-hands.dev>

neubig commented May 7, 2026

Copy link
Copy Markdown
Member Author

✅ Full SDK test suite: 3573 passed, 0 failed (uv run pytest tests/sdk --timeout=20).

Two tests deselected are pre-existing environmental failures, both confirmed independent of this PR by reproducing them on main:

  • tests/sdk/conversation/local/test_conversation_core.py::test_conversation_large_event_handling — hangs in this sandbox (no LLM/network); also hangs on main.
  • tests/sdk/agent/test_acp_agent.py::TestACPSecretsEnvInjection::test_static_secret_injected_into_subprocess_env — the sandbox's secret-injection layer rewrites GITHUB_TOKEN in the subprocess env, so the assertion env.get("GITHUB_TOKEN") == "ghp_test123" fails with the real token. Pre-existing on main.

Includes a follow-up commit (a76818d) that updates test_base_span_management.py to patch the new start_root_span/end_root_span symbols and asserts the new idempotency guarantee.

— OpenHands

@github-actions

github-actions Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/observability
   laminar.py1845470%37–41, 104, 172–173, 186–187, 213–214, 254, 258–259, 262–265, 268–275, 285–289, 308–309, 312–314, 318, 320–321, 326, 330, 382, 396, 440, 462–465, 498–500, 502–503
TOTAL25513723171% 

- Drop now-unused TYPE_CHECKING import of opentelemetry.trace from
  observability/laminar.py (referenced only by the old SpanManager).
- Reorder imports in the new regression tests to satisfy ruff isort.

Co-authored-by: openhands <openhands@all-hands.dev>
…n shims

Audit on 2026-05-07 found *zero* callers of these symbols outside the SDK
itself:
- 0 hits in OpenHands/OpenHands (grep + GitHub code search)
- 0 hits in OpenHands/agent-canvas (TypeScript-only)
- 0 hits in OpenHands/codescout (only ``maybe_init_laminar`` is imported)
- 0 hits elsewhere in the OpenHands org via GitHub code search

The shims are kept solely to protect any unaudited private/external
consumer. To make the schedule explicit, every shim now calls
``warn_deprecated`` with:

    deprecated_in="1.22.0"   # this PR ships in 1.22.0
    removed_in="1.27.0"      # 5-minor-version grace window matches the
                             # SDK's existing precedent for
                             # VerificationSettings.confirmation_mode
                             # (deprecated 1.17.0, removed 1.22.0)

The warning is silent during 1.21.x development and activates the moment
1.22.0 ships. ``_get_span_manager`` was tweaked to construct the legacy
``SpanManager`` via ``__new__`` so wiring up the singleton doesn't itself
emit a deprecation warning.

Adds ``test_deprecated_shims_emit_warnings`` which patches
``_current_version`` to 1.22.0 and asserts each shim emits the expected
``DeprecationWarning``.

Co-authored-by: openhands <openhands@all-hands.dev>

neubig commented May 7, 2026

Copy link
Copy Markdown
Member Author

Deprecation schedule + downstream-consumer audit

To answer the question of how long to keep the backwards-compat shims (SpanManager, start_active_span, end_active_span), I ran a downstream-consumer audit and added a formal schedule (commit e37ace5).

Audit results (2026-05-07):

Search target Hits Notes
OpenHands/OpenHands (grep on full clone) 0 nothing imports these symbols
OpenHands/agent-canvas 0 TypeScript only — no Python at all
OpenHands/codescout 1 file imports only maybe_init_laminar (untouched)
Org-wide gh search code start_active_span org:OpenHands 0
Global from openhands.sdk.observability.laminar import … only the SDK itself, forks of it, and a benchmark that vendors the SDK source

So in practice no first- or second-party caller uses the deprecated symbols. The shims now exist purely to give any unaudited private consumer a heads-up before the SDK simply removes them.

Schedule (matches existing SDK precedent):

deprecated_in = "1.22.0"   # this PR ships in 1.22.0
removed_in    = "1.27.0"   # 5-minor-version grace window

This matches the SDK's previous VerificationSettings.confirmation_mode deprecation (deprecated 1.17.0 / removed 1.22.0). Each shim now calls warn_deprecated(...) so:

  • Calls on 1.22.0–1.26.x emit DeprecationWarning.
  • Calls on 1.27.0+ emit UnsupportedWarning (and the maintainer can delete the shims at that point).
  • Calls during 1.21.x development are silent — the warning helper checks current_version >= deprecated_in before firing.

Re transitioning OpenHands/OpenHands or agent-canvas: nothing to transition. Both repos are clean. The only transition needed was inside this SDK itself, which the rest of this PR already handles (BaseConversation now uses start_root_span / end_root_span directly).

Added test_deprecated_shims_emit_warnings (patches _current_version to "1.22.0") so the warning contract is locked in for CI.

— OpenHands

…s.py

The repo's .github/scripts/check_deprecations.py walks the AST and only
accepts string literals (or date.today()) for deprecated_in / removed_in.
The previous commit factored these out to module-level Final[str]
constants which the scanner rejects as "Unsupported removed_in
expression". Inline the literal strings to satisfy the scanner — the
human-readable schedule comment at the top of the shim block still
documents the policy.

Co-authored-by: openhands <openhands@all-hands.dev>
@neubig
neubig marked this pull request as ready for review May 7, 2026 22:34

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Good taste - Elegant solution that eliminates the root cause

Excellent problem analysis and fix. The switch from a global LIFO stack (SpanManager) to per-conversation owned RootSpan objects is exactly the right data structure choice — it eliminates both the cross-async-context bug and the concurrent-conversation collision bug at once.

The @observe decorator change is minimal and clean: re-attach the owner's root span at every entry point via Laminar.use_span, which is the pattern Laminar explicitly recommends in their docs. The three regression tests directly target the bugs and prove the fix works, including the isolated-context scenario that reproduced the 63% orphan rate.

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟢 LOW

This changes internal observability instrumentation only. The fix makes traces more correct (child spans properly nested under conversation root) without affecting agent behavior, tool execution, or benchmark performance. Backward-compatible shims preserve the old API with proper deprecation warnings (1.22.0 → 1.27.0, following the 5-minor-version policy). The new pattern is upstream-recommended and the old global stack had no external callers per the org-wide audit.

VERDICT:
✅ Worth merging - Solves a real production problem (63% orphan traces) with a clean, well-tested fix.

KEY INSIGHT:
Per-object span ownership + entry-point re-attachment via use_span is the correct pattern for trace propagation across async/thread boundaries where contextvars breaks down.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ QA Report: PASS

The PR successfully fixes orphaned Laminar traces by ensuring child spans correctly attach to the conversation root span across async contexts.

Does this PR achieve its stated goal?

Yes. The PR fixes the orphan trace bug where ~63% of conversations showed up as split traces in Laminar. The fix ensures that all child spans (conversation.send_message, conversation.run, agent.step, tool calls) correctly nest under the conversation root span with proper session_id propagation, regardless of which async task or thread invokes the methods. This addresses the root cause (contextvars failing to propagate across async boundaries) by switching to the upstream-recommended start_span + use_span pattern.

Phase Result
Environment Setup ✅ Built successfully via make build
CI Status ✅ 30 checks passing, 0 failing
Functional Verification ✅ All behaviors verified
Functional Verification

Test 1: Unit tests verify the fix

Ran the observability test suite:

python -m pytest tests/sdk/observability/test_laminar.py -v

Result: All 29 tests passed, including the 3 new regression tests:

  • test_observe_calls_use_span_with_owner_root_span_on_sync ✅
  • test_observe_calls_use_span_with_owner_root_span_on_async ✅ (the key cross-context bug scenario)
  • test_two_concurrent_conversations_do_not_collide ✅
  • test_deprecated_shims_emit_warnings ✅

Interpretation: The tests prove that:

  1. The @observe decorator calls Laminar.use_span() with the owner's root span at every entry point
  2. This works even when methods are called from isolated async contexts (the bug scenario)
  3. Concurrent conversations get independent root spans (no global stack collision)
  4. Deprecated APIs still work and emit proper warnings

Test 2: Cross-context span propagation demonstration

Created a demonstration script that:

  1. Creates a conversation with a root span
  2. Calls @observe-decorated methods from the same async context
  3. Calls @observe-decorated methods from a fresh, isolated async context (simulating the bug)
  4. Tracks all Laminar.use_span() calls via mocking

Result: use_span() was called with the correct root span in ALL cases, including when invoked from an isolated context with no parent contextvars.

Interpretation: This proves the fix works. Before the fix, calling a conversation method from a different async task (e.g., RemoteConversation handling a websocket message) would start a fresh root trace because contextvars don't propagate to pre-existing tasks. After the fix, the root span is stored on the conversation object and explicitly re-attached at every entry point, so cross-context calls work correctly.


Test 3: Concurrent conversations don't collide

Created two concurrent conversation objects and verified:

  1. Each gets its own independent root span
  2. Ending conversation 2's span doesn't affect conversation 1
  3. Each span ends independently

Result: Both conversations maintained independent root spans throughout their lifecycle.

Interpretation: This proves the global SpanManager LIFO stack bug is fixed. Before the fix, two concurrent conversations would push/pop from a shared stack, causing the second conversation to corrupt the first's span on close. After the fix, each conversation owns its root span, so they can coexist safely.


Test 4: Backward compatibility maintained

Tested the deprecated start_active_span() and end_active_span() APIs:

Result: Both deprecated functions still work and emit proper DeprecationWarning messages indicating:

  • deprecated_in="1.22.0"
  • removed_in="1.27.0"
  • Clear migration guidance to start_root_span() / end_root_span()

Interpretation: External users who may have imported these APIs (though the PR description notes an org-wide audit found zero external usages) get a 5-minor-version grace period to migrate, with clear warnings and migration instructions.

Issues Found

None.


Verdict: This PR delivers exactly what it promises. The orphan trace bug is fixed via the correct architectural approach (per-conversation root span ownership + explicit re-attachment), the fix is comprehensively tested, backward compatibility is maintained, and CI is green. Ready to merge.

@xingyaoww xingyaoww left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's try this :)

@neubig
neubig merged commit ab5fa33 into main May 8, 2026
41 checks passed
@neubig
neubig deleted the fix/observability-cross-context-trace-propagation branch May 8, 2026 12:12
StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
pengzhang-create pushed a commit to Pyromind-Dynamics/software-agent-sdk that referenced this pull request Aug 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants